<!--
 * @Descripttion: 标准化商品分类属性
 * @version:
 * @Author: fqiao
 * @Date: 2023-6-28 10:34:28 
-->
<template>
  <div>
    <el-row type="flex" :gutter="5">
      <el-col :span="4">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <i class="el-icon-menu orgIcon"></i>
            <span>商品类型目录</span>
          </div>
          <div class="category-tree-head-search">
            <el-input size="mini" placeholder="请输入关键字" v-model="filterCategory" clearable />
          </div>
          <el-tree class="tree tree-category" :style="treeHeight" ref="treeCategory" :data="categoryList"
            :default-checked-keys="categoryAuthList" highlight-current :props="{ label: categoryTreeLabel }"
            :filter-node-method="filterNodeCategory" node-key="key" @node-click="handleCheckChange">
            <div class="tree-item" slot-scope="{ node, data }">
              <!-- <el-tooltip :content="node.label" placement="bottom" effect="dark"> -->
                <div class="item">{{ node.label }}</div>
              <!-- </el-tooltip> -->
            </div>
          </el-tree>
        </el-card>
      </el-col>
      <el-col :span="20">
        <el-card class="content-card">
          <!-- 筛选 -->
          <div class="control-area"> 
            <e-control :search-form-options="formOptions" :search-label-width="searchLabelWidth" :searchInsertShow="true"
              @on-search="searchControlHandle" @on-refresh="refreshControlHandle" @change-height="changeControlHeight"
              @on-insert="insertControlHandle" @on-setPropsValue="handleSetPropsValue"></e-control>
          </div>
          <!-- 属性列表 -->
          <e-table :data="propertyList" :columns="columns" ref="multipleTable" stripe border :maxHeight="tableMaxHeight"
            style="width: 100%" @selection-change="changeTableSelectData" :current="pageData.pageNum"
            :total="pageData.total" @page-size-change="changePageSize" @page-current-change="changePageCurrent">
            <template slot-scope="{scope}" slot="operation" >
              <el-tooltip content="编辑" placement="top">
                <el-button @click="updateTableHandle(scope.row)" type="warning" size="mini" icon="el-icon-edit-outline"
                  plain></el-button>
              </el-tooltip>
              <!-- <el-tooltip content="商品属性值" placement="top">
                <el-button @click="handleSetPropsValue(scope.row)" type="primary" size="mini" icon="el-icon-document"
                  plain></el-button>
              </el-tooltip> -->
            </template>
          </e-table>
        </el-card>
      </el-col>
    </el-row>
    <!-- 编辑属性信息弹窗 -->
    <el-dialog :title="editDialogTitle" :visible.sync="editDialogShow" :close-on-click-modal="false"
      :close-on-press-escape="false" @close="cancelDialogDataHandle" width="70%">
      <e-form ref="dialogForm" :form-options="editFormOptions" :form-label-width="editFormLabelWidth"
        :form-rules="editFormRules" :form-data-current="dialogFormCurrent"></e-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelDialogDataHandle">取 消</el-button>
        <el-button type="primary" @click="saveDialogDataHandle">保 存</el-button>
      </span>
    </el-dialog>
    <!--  商品属性值列表  -->
    <el-dialog title="商品属性值列表" :visible.sync="tableDialogShow" :close-on-click-modal="false"
      :close-on-press-escape="false" @close="closeTableDialog" width="50%">
      <el-button class="dialog-add-btn" @click="insertDialogTableHandle()" type="success" size="mini" plain>添加</el-button>
      <e-table :data="dialogTableData" :columns="dialogColumns" ref="multipleTable" stripe border :maxHeight="400"
        style="width: 100%" :current="dialogPageData.current" :total="dialogPageData.total"
        @page-size-change="changeDialogPageSize" @page-current-change="changeDialogPageCurrent">
        <template slot-scope="{scope}" slot="propertyValue">
          <el-popover placement="top" trigger="hover">
            <div class="cell-content">{{ scope.row.propertyValue }}</div>
            <p class="overflow" slot="reference">{{ scope.row.propertyValue }}</p>
          </el-popover>
        </template>
        <template slot-scope="{scope}" slot="operation">
          <el-tooltip content="编辑" placement="top">
            <el-button @click="updateDialogTableHandle(scope.row)" type="warning" size="mini" icon="el-icon-edit-outline"
              plain></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button @click="deleteDialogTableHandle(scope.row)" type="danger" size="mini" icon="el-icon-delete"
              plain></el-button>
          </el-tooltip>
        </template>
      </e-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelPurchaseDialogDataHandle">确定</el-button> 
      </span>
    </el-dialog>
    <el-dialog :title="editDialogTitle" :visible.sync="editTableDialogShow" :close-on-click-modal="false"
      :close-on-press-escape="false" @close="cancelTableDialogDataHandle" width="50%">
      <e-form ref="tableDialogForm" :form-options="editTableFormOptions" :form-label-width="editTableFormLabelWidth"
        :form-rules="editFormOptionsRules" :form-data-current="tableDialogFormCurrent"></e-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelTableDialogDataHandle">取 消</el-button>
        <el-button type="primary" @click="saveTableDialogDataHandle">保 存</el-button>
      </span>
    </el-dialog>

    <el-dialog :title="editPurchaseDialogTitle" :visible.sync="editPurchaseTableDialogShow" :close-on-click-modal="false"
      :close-on-press-escape="false" @close="cancelPurchaseTableDialogDataHandle" width="50%">
      <e-form ref="tablePurchaseDialogForm" :form-options="editPurchaseTableFormOptions"
        :form-label-width="editPurchaseTableFormLabelWidth" :form-rules="editPurchaseFormRules"
        :form-data-current="tablePurchaseDialogFormCurrent"></e-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelPurchaseTableDialogDataHandle">取 消</el-button>
        <el-button type="primary" @click="savePurchaseTableDialogDataHandle">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import eManage from '@/components/e-manage'
import eControl from '@/components/e-control'
import eForm from '@/components/e-form'
import { formOptions, btns } from './control'
import { columns, dialogColumns } from './columns'
import { editFormOptions, editTableFormOptions, editFormOptionsRules, editFormRules, editPurchaseTableFormOptions, editPurchaseFormRules } from './form'
import {
  getQueryItemTrees,
  getAllInputType,
  editGoodsProperty,
  addGoodsProperty,
  getAllItemRules,
  queryGoodsPropertyValueList,
  editGoodsPropertyValue,
  addGoodsPropertyValue,
  propertyValuePurchaserAdd,
  propertyValuePurchaserEdit,
  deletePropertyValue,
} from '@/api/admin.api'
import { allCategory } from "@/api/supplierActivity/supplier";
import {
  getItemPropertyListApi,
  getDictionaryListByType
} from "@/api/supplierActivity/goods.admin";

export default {
  name: 'standardized-commodity-category-library',
  components: {
    eManage,
    eControl,
    eForm
  },
  data() {
    return {
      formOptions,
      searchLabelWidth: '180px',
      btns,
      columns,
      // 弹出框表单
      dialogColumns,
      editFormOptions,
      editFormOptionsRules,
      editTableFormOptions,
      editFormLabelWidth: '200px',
      editTableFormLabelWidth: '120px',
      editFormRules,

      // 编辑框是否展示
      editDialogShow: false,
      // 编辑框类型 0:新增;1:修改;
      editDialogType: 0,
      // 编辑框表单数据
      dialogFormCurrent: {
        isMain: '1',
        isPurchaserMust: '1',
        isSupplierMust: '1',
        v: '1',
        isSearch: '1',
        isPurchaseSearch: '1',
        columnType: 'varchar'
      },
      // 查询表单
      searchFormData: {},
      // 控制区高度
      controlHeight: 0,
      // 表格数据
      propertyList: [],
      // 分页数据
      pageData: {
        // 当前分页
        pageNum: 1,
        // 分页条数
        pageSize: 10,
        // 数据总数
        total: 0
      },
      // 表格选中数据
      tableSelectData: [],

      // 弹出框列表的编辑框类型 0:新增;1:修改;
      tableDialogType: 0,
      // 弹出框列表的控制弹出框显示
      tableDialogShow: false,
      // 弹出框列表的初始化数据
      tableDialogFormCurrent: {
        v: '1'
      },
      // 弹出框列表的分页信息
      dialogPageData: {
        // 当前分页
        pageNum: 1,
        // 分页条数
        pageSize: 10,
        // 数据总数
        total: 0
      },
      // 弹出框列表的数据源
      dialogTableData: [],
      // 弹出框列表的选中数据
      dialogTableSelectData: [],
      // 弹出列表页的弹出编辑框
      editTableDialogShow: false,
      // 当前属性（设置属性值使用）
      currentProperty: {},
      // 左侧树选中目录
      categoryAuthList: [],
      categoryList: [],
      treeSelectData: "",
      filterCategory: "",
      // 弹出框采购属性值列表的分页信息
      purchaseDialogPageData: {
        // 当前分页
        pageNum: 1,
        // 分页条数
        pageSize: 10,
        // 数据总数
        total: 0
      },
      // 当前采购人采购属性值
      purchaseCurrentProperty: {},
      // 弹出框采购属性值列表的编辑框类型 0:新增;1:修改;
      purchaseTableDialogType: 0,
      editPurchaseTableDialogShow: false,
      editPurchaseTableFormLabelWidth: '120px',
      editPurchaseTableFormOptions,
      editPurchaseFormRules,
      tablePurchaseDialogFormCurrent: {}
    }
  },
  watch: {
    filterCategory(val) {
      this.$refs.treeCategory.filter(val)
    },
  },
  computed: {
    // 组合查询条件和分页
    searchData() {
      const { pageNum, pageSize } = this.pageData;
      return { ...this.searchFormData, pageSize, pageNum, fkItemCategoryId: this.treeSelectData }
    },
    // 属性表单实例
    dialogForm() {
      return this.$refs.dialogForm
    },
    // 属性值表单实例
    tableDialogForm() {
      return this.$refs.tableDialogForm
    },
    // 属性值表单实例
    purchaseTableDialogForm() {
      return this.$refs.tablePurchaseDialogForm
    },
    //表格最大高度
    tableMaxHeight() {
      return window.innerHeight - this.controlHeight - 280
    },
    // 编辑框标题
    editDialogTitle() {
      return this.editDialogType === 0 ? '新增' : '编辑'
    },
    editPurchaseDialogTitle() {
      return this.purchaseTableDialogType === 0 ? '新增' : '编辑'
    },
    // 左侧树
    treeHeight() {
      return {
        'height': window.innerHeight - 240 + 'px',
        'overflowY': 'scroll'
      }
    },
    treeRef() {
      return this.$refs['listTree']
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      // this.getPropertyList()
      // this.getOrgTreeEvent()
      this.getLabelData();
      this.getCategoryTree();
    },
    searchControlHandle(data) {
      this.searchFormData = data
      // console.log(data)
      this.refreshPageCurrent()
    },
    // 重置
    refreshControlHandle(data) {
      console.log('refreshControlHandle',data)
      this.searchFormData = data;
      this.getPropertyList()

    },
    changeControlHeight(height) {
      this.controlHeight = height
    },
    insertControlHandle() {
      if (this.treeSelectData.length > 0) {
        this.openDialog()
      }
      else {
        this.$alert('请选择商品目录！', '提示', {
          confirmButtonText: '确定'
        })
      }
    },
    insertDialogTableHandle() {
      this.openTableDialog()
    },
    changeTableSelectData(rows) {
      this.tableSelectData = rows
    },
    changePageSize(size) {
      this.pageData.pageSize = size
      this.getPropertyList()
    },
    // 修改弹出列表分页条数
    changeDialogPageSize(size) {
      this.dialogPageData.pageSize = size
      this.getDialogTableData(this.currentProperty.id)
    },
    changePageCurrent(current) {
      this.pageData.pageNum = current
      this.getPropertyList()
    },
    // 弹出框列表的当前页
    changeDialogPageCurrent(current) {
      this.dialogPageData.pageNum = current
      this.getDialogTableData(this.currentProperty.id)
    },
    refreshPageCurrent() {
      this.pageData.pageNum = 1
      this.getPropertyList()
    },
    // 弹出框列表重置当前分页
    refreshDialogPageCurrent() {
      this.dialogPageData.pageNum = 1
      this.getDialogTableData(this.currentProperty.id)
    },
    getPropertyList() {  
      if (this.treeSelectData) {
        getItemPropertyListApi(this.searchData).then(res => {
          this.propertyList = res.rows
          this.pageData.total = res.total
        })
      }
      else {
        this.$message({
          message: '请选择商品类型',
          type: 'warning'
        })
      }
    },
    // 获取选项数据
    getLabelData() {
      // 获取商品输入类型 2023.07.17
      getDictionaryListByType("00027").then(res => { 
        console.log("00027",res);
      })
      
      // getAllInputType().then(res => {
      //   // console.log(res)
      //   res.map((item, index) => {
      //     const optionObj = {}
      //     optionObj.label = item.optional1
      //     optionObj.value = item.dictionaryKey1
      //     this.$set(editFormOptions[0].options, index, optionObj)
      //     this.$set(editFormOptions[1].options, index, optionObj)
      //     this.$set(formOptions[1].options, index, optionObj)
      //   })
      // })
    },
    getDialogTableData(propId) {
      const { pageNum, pageSize } = this.dialogPageData
      queryGoodsPropertyValueList(propId, { size: pageSize, current: pageNum }).then(res => {
        this.dialogTableData = res.records
        this.dialogPageData.total = res.total
      })
    },
    categoryTreeLabel(data, node) { 
      return data.categoryName // data.node.categoryName
    },
    getCategoryTree() {
      console.log('allCategory-------');
      allCategory().then(res => {
        this.categoryList = res
      })
    },
    filterNodeCategory(value, data) {
      if (!value.toUpperCase()) return true
      return data.categoryName.toUpperCase().indexOf(value.toUpperCase()) !== -1
    }, 
    // 获取组织树
    // getOrgTreeEvent () {
    //   getQueryItemTrees({ categorylevel: '1' }).then((res) => {
    //     const newArr = []
    //     res.map(item => {
    //       const obj = {}
    //       obj.label = item.category_name
    //       obj.categoryId = item.id
    //       obj.categorylevel = item.category_level + 1
    //       obj.check = item.check
    //       newArr.push(obj)
    //     })
    //     this.treeData = newArr
    //   })
    // },
    // 提交添加属性数据
    addProperty(data) {
      addGoodsProperty(data).then(res => {
        // console.log(res)
        this.dialogForm.handleRefresh()
        this.closeDialog()
        this.$message({
          message: '保存成功',
          type: 'success'
        })
        this.refreshPageCurrent()
      })
    },
    // 提交编辑属性数据
    updateProperty(data) {
      editGoodsProperty(data).then(res => {
        // console.log(res)
        this.dialogForm.handleRefresh()
        this.closeDialog()
        this.$message({
          message: '保存成功',
          type: 'success'
        })
        this.refreshPageCurrent()
      })
    },
    updateTableHandle(row) {
      this.dialogFormCurrent = { ...row }
      this.openDialog(1)
    },
    updateDialogTableHandle(row) {
      this.tableDialogFormCurrent = { ...row }
      this.openTableDialog(1)
    },
    // 删除商品属性值
    deleteDialogTableHandle(row) {
      deletePropertyValue(row.id).then(() => {
        this.$message({
          message: '删除成功',
          type: 'success'
        })
        this.getDialogTableData(this.currentProperty.id)
      })
    },
    // 懒加载左侧tree
    loadNode(node, resolve) {
      if (node.level === 1) {
        getQueryItemTrees({ categorylevel: node.data.categorylevel, categoryId: node.data.categoryId }).then((res) => {
          const secArr = []
          res.map(item => {
            const obj = {}
            obj.label = item.category_name
            obj.categoryId = item.id
            obj.categorylevel = item.category_level + 1
            obj.check = item.check
            secArr.push(obj)
          })
          return resolve(secArr)
        })
      }
      if (node.level === 2) {
        getQueryItemTrees({ categorylevel: node.data.categorylevel, categoryId: node.data.categoryId }).then((res) => {
          const thrArr = []
          res.map(item => {
            const obj = {}
            obj.label = item.category_name
            obj.categoryId = item.id
            obj.categorylevel = item.category_level + 1
            obj.check = item.check
            obj.leaf = true
            thrArr.push(obj)
          })
          return resolve(thrArr)
        })
      }
    },
    // 上传属性值
    submmitPropertyValue() {
      const property = this.currentProperty
      const params = {
        ...this.tableDialogForm.formData,
        fkGodPropertyId: property.id,
      }
      if (this.tableDialogType === 0) {
        addGoodsPropertyValue(params).then(res => {
          this.tableDialogForm.handleRefresh()
          this.closeTableDialog()
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          this.refreshDialogPageCurrent()
        })
      }
      else {
        editGoodsPropertyValue(params).then(res => {
          this.tableDialogForm.handleRefresh()
          this.closeTableDialog()
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          this.refreshDialogPageCurrent()
        })
      }
    },
    openDialog(type = 0) {
      this.editDialogType = type
      if (type === 2) {
        this.tableDialogShow = true
      }
      else {
        this.editDialogShow = true
      }
    },
    openTableDialog(type = 0) {
      this.tableDialogType = type
      this.editTableDialogShow = true
    },
    closeDialog() {
      if (this.editDialogType === 2) {
        this.tableDialogShow = false
      }
      else {
        this.editDialogShow = false
      }
      this.editDialogType = 0
    },
    closeTableDialog() {
      this.editTableDialogShow = false
      this.tableDialogType = 0
    },
    saveDialogDataHandle() {
      // console.log(this.dialogForm.formData)
      this.$refs['dialogForm'].handleValidate((valid) => {
        if (!valid) {
          this.$message({
            message: '请检查表单填写内容',
            type: 'warning'
          })
          return
        }
        if (this.editDialogType === 0) {
          const data = {
            ...this.dialogForm.formData,
            fkItemCategoryId: this.treeSelectData
          }
          this.addProperty(data)
        }
        else if (this.editDialogType === 1) {
          const data = {
            ...this.dialogForm.formData,
          }
          this.updateProperty(data)
        }
      })
    },
    // 弹出框列表保存弹框数据
    saveTableDialogDataHandle() {
      const self = this
      this.tableDialogForm.handleValidate(v => {
        if (v) {
          self.submmitPropertyValue()
        }
      })
    },
    // 处理采购人采购属性值新增
    savePurchaseTableDialogDataHandle() {
      const self = this
      this.purchaseTableDialogForm.handleValidate(v => {
        if (v) {
          // 新增
          if (self.purchaseTableDialogType === 0) {
            propertyValuePurchaserAdd({
              ...self.purchaseTableDialogForm.formData,
              fkGodPropertyId: self.purchaseCurrentProperty.id
            })
              .then(() => {
                self.$message({
                  message: '添加成功',
                  type: 'success'
                })
                self.purchaseTableDialogForm.handleRefresh()
                self.editPurchaseTableDialogShow = false
                self.getPurchaseDialogTableData(self.purchaseCurrentProperty.id)
              })
          }
          // 编辑
          if (self.purchaseTableDialogType === 1) {
            propertyValuePurchaserEdit({
              ...self.purchaseTableDialogForm.formData,
              id: self.tablePurchaseDialogFormCurrent.id,
              fkGodPropertyId: self.purchaseCurrentProperty.id
            })
              .then(() => {
                self.$message({
                  message: '修改成功',
                  type: 'success'
                })
                self.purchaseTableDialogForm.handleRefresh()
                self.editPurchaseTableDialogShow = false
                self.getPurchaseDialogTableData(self.purchaseCurrentProperty.id)
              })
          }
        }
      })
    },
    cancelDialogDataHandle() {
      if (this.dialogForm) {
        this.dialogForm.handleRefresh()
        this.dialogFormCurrent = {
          isMain: '1',
          isPurchaserMust: '1',
          isSupplierMust: '1',
          v: '1',
          isSearch: '1',
          isPurchaseSearch: '1',
          columnType: 'varchar'
        }
      }
      this.closeDialog()
    },
    cancelPurchaseDialogDataHandle() {
      if (this.tableDialogForm) {
        this.tableDialogForm.handleRefresh()
        this.dialogFormCurrent = {
          isMain: '1',
          isPurchaserMust: '1',
          isSupplierMust: '1',
          v: '1',
          isSearch: '1',
          isPurchaseSearch: '1',
          columnType: 'varchar'
        }
      }
      this.closeDialog()
    },
    // 处理点击取消按钮
    cancelTableDialogDataHandle() {
      if (this.tableDialogForm) {
        this.tableDialogForm.handleRefresh()
      }
      this.tableDialogFormCurrent = { v: '1' }
      this.closeTableDialog()
    },
    // 处理采购人采购属性值关闭
    cancelPurchaseTableDialogDataHandle() {
      if (this.purchaseTableDialogForm) {
        this.purchaseTableDialogForm.handleRefresh()
      }
      this.tablePurchaseDialogFormCurrent = { v: '1' }
      this.editPurchaseTableDialogShow = false
      this.purchaseTableDialogType = 0
    },
    
    handleCheckChange(data) { 
      console.log(data)
      if (data.id) { 
          this.treeSelectData = data.id
          this.getPropertyList()
      }
    },

    handleSetPropsValue(row) {
      this.openDialog(2)
      this.currentProperty = row
      this.getDialogTableData(this.currentProperty.id)
    },
  }
}
</script>

<style lang="scss">
.box-card {
  margin: 4px;
  height: calc(100vh - 120px);
  overflow: scroll;

  .category-tree-head-search {
    width: 100%;
  }

  .tree-item {
    width: 100%
  }
}

.content-card {
  overflow: scroll;
  margin: 4px;
  height: calc(100vh - 120px);

  .el-card__body {
    padding: 10px;
  }

  .el-table {
    margin-top: 20px;
  }

  .el-pagination {
    text-align: right;
  }

  .control-area {
    margin-bottom: 10px;
  }
}

.abc-header {
  color: #0000ff;
}

.abc {
  font-weight: bold;
  color: #e53939;
}

.selectRole {
  padding: 30px;
  box-sizing: border-box;

  .el-select {
    width: 100%;
  }
}

.dialog-add-btn {
  margin: 10px;
}

.cell-content {
  width: 200px;
  min-height: 20px;
  max-height: 200px;
  overflow-y: auto;
}

.overflow {
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
  overflow: hidden;
}
</style>

